package cool.mtc.minghe.service.service.websocket.impl;

import cool.mtc.core.util.CollectionUtil;
import cool.mtc.minghe.data.model.websocket.dto.WebSocketOnlineUserDTO;
import cool.mtc.minghe.service.manager.websocket.WebSocketManager;
import cool.mtc.minghe.service.service.BaseServiceImpl;
import cool.mtc.minghe.service.service.websocket.WebSocketService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 明河
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSocketServiceImpl extends BaseServiceImpl implements WebSocketService {
    private final WebSocketManager webSocketManager;

    @Override
    public void online(WebSocketOnlineUserDTO onlineUser) {
        this.addOnlineUser(onlineUser);
    }

    @Override
    public void offline(String sessionId) {
        WebSocketOnlineUserDTO onlineUser = new WebSocketOnlineUserDTO();
        onlineUser.setSessionId(sessionId);
        this.removeOnlineUser(onlineUser);
    }

    /**
     * 增加在线用户
     */
    private void addOnlineUser(WebSocketOnlineUserDTO onlineUser) {
        List<WebSocketOnlineUserDTO> onlineUserList = webSocketManager.listOnlineUser();
        onlineUserList.add(onlineUser);
        webSocketManager.updateOnlineUser(onlineUserList);
    }

    /**
     * 移除在线用户
     */
    private void removeOnlineUser(WebSocketOnlineUserDTO onlineUser) {
        List<WebSocketOnlineUserDTO> onlineUserList = webSocketManager.listOnlineUser();
        if (CollectionUtil.isEmpty(onlineUserList)) {
            return;
        }
        onlineUserList.remove(onlineUser);
        webSocketManager.updateOnlineUser(onlineUserList);
    }
}
